<template>
  <basic-container>
    <el-breadcrumb class="projectNameCrumb">
        <el-breadcrumb-item class="projectNameCrumbItem">
          <span>当前项目：</span>
          {{projectInfo.projectName}}
        </el-breadcrumb-item>
    </el-breadcrumb>
    <el-container> 
      <el-aside width="260px">
          <avue-tree :option="treeOption" :data="treeData" @node-click="treeNodeClick">
          </avue-tree>
      </el-aside>
      <el-main>
        <avue-crud :option="option"
                  :table-loading="loading"
                  :data="data"
                  ref="crud"
                  v-model="form"
                  :defaults.sync="showColumn"
                  :permission="permissionList"
                  :before-open="beforeOpen"
                  @sortable-change="sortableChange"
                  @row-del="rowDel"
                  @row-update="rowUpdate"
                  @row-save="rowSave"
                  @refresh-change="refreshChange"
                  @search-change="searchChange"
                  @search-reset="searchReset"
                  @selection-change="selectionChange"
                  @current-change="currentChange"
                  @size-change="sizeChange"
                  @filter="filterChange"
                  @sort-change="sortChange"
                  @row-dblclick="handleRowDBLClick"               
                  @on-load="onLoadUser">
          <template slot-scope="scope" slot="menu">
          </template>
          <template slot-scope="scope" slot="menuLeft">
            <el-button type="primary"
                      size="small"
                      icon="el-icon-plus"
                      v-if="permission.general_project_u_batch_add"
                      @click.stop="openAddUserDialog">批量新增
            </el-button>
            <el-button type="danger"
                      size="small"
                      icon="el-icon-delete"
                      v-if="permission.general_project_u_batch_delete"
                      @click.stop="handleDelete">删 除
            </el-button>
          </template>
          <template slot="menuRight">
            <el-button  v-if="permission.general_project_u_download" type="default" @click.stop="exportExcel"  title="下载" icon="el-icon-download" circle size="small"></el-button>
          </template>
        </avue-crud>
      </el-main>
    </el-container> 
    <!-- 
      批量添加用户对话框
     -->
    <el-dialog title="批量添加用户" :fullscreen='true' :close-on-click-modal='false' :visible.sync="addUserDialog">
      <sys-user-info-dialog 
        ref="childDialog"
        :hasSelectIds="oldUserListValue"
        @handleBatchAdd="handleBatchAdd">
      </sys-user-info-dialog>
    </el-dialog>
  </basic-container>
</template>

<script>
import {querySysGroupInfoListPage} from '@/api/system/sysGroupInfoApi';
import {exportSysUserGroupRelationExcel,saveOrUpdateSysUserGroupRelation,saveOrUpdateSysUserGroupRelationList,saveSysUserGroupRelation,saveSysUserGroupRelationList,deleteSysUserGroupRelation,querySysUserGroupRelation,querySysUserGroupRelationListPage,updateSysUserGroupRelation,deleteSysUserGroupRelationList} from '@/api/system/sysUserGroupRelationApi';
import {mapGetters} from 'vuex';
import { reqCommonMsg } from '@/util/reqCommonMsg';
import {filterFormat} from '@/util/util';
import SysUserInfoDialog from '@/views/system/sysUserInfoDialog.vue'
export default {
  
  data() {
    return {
      //添加用户对话框
      fullscreenLoading: false,
      currentRow: {},

      importDataArea: '',
      addUserDialog: false,
      isFirstOpen: true,
      userListValue: [],
      oldUserListValue: [],

      form: {},
      selectionList: [],
      loading: false, 
      showColumn: [],
      option: {
        labelPosition: 'right',
        labelSuffix: '：',
        labelWidth: 120,
        dialogTop: '50',
        indexFixed:true, 
        stripe:true,
        calcHeight: 80,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        selection: true,
        addBtn: false,
        viewBtn: true,
        delBtn: false,
        cancelBtn: true,
        printBtn:false,
        editBtn:false,
        saveBtn: false,
        filterBtn:true,          
        menuWidth: 100,
        dialogMenuPosition: 'center',
        dialogDirection:'rtl',
        dialogType:'dialog',
        dialogFullscreen:false,
        dialogClickModal:false,
        dialogWidth: '70%',
        highlightCurrentRow:  true,
        searchShow:true,
        column: [
          
          {
            label: '用户ID',
            prop: 'userId', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            width: 160,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '用户名',
            prop: 'userName', 
            type: 'input', 
            search: true,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '真实姓名',
            prop: 'realName', 
            type: 'input', 
            search: true,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '所属机构号',
            prop: 'belongOrgNo', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '所属机构名称',
            prop: 'belongOrgName', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            width: 200,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          }
        ]
      },
      data: [],
      // 组织机构树形区
      checkedNode: '',
      currentGroup: {},
      orgType: '1',
      treeData:[],
      treeOption:{
        addBtn: false,
        menu: false,
        defaultExpandAll:false,
        props: {
          label: 'userGroupName',
          value: 'id'
        },
      },
      // 请求参数区
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      reqParams: {
        singleBody: {},
        listBody: [{}],
        sqlCondition:[],
        orderRule: {},
        currentPage: 1,
        pageSize: 10
      },
      commonData: null,
      conditions: [],
      orderRules: [],
      singleBody: {}
    };
  },
  components: {
    SysUserInfoDialog
  },
  computed: {
    ...mapGetters(['website','userInfo','orgTree','permission','projectInfo']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.general_project_u_add, false),
        viewBtn: this.vaildData(this.permission.general_project_u_view, false),
        delBtn: this.vaildData(this.permission.general_project_u_delete, false),
        editBtn: this.vaildData(this.permission.general_project_u_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push({id : ele.id});
      });
      return ids;
    } 
  },
  methods: {
    /**
     * 打开添加用户对话框
     */
    openAddUserDialog(){
      if(this.currentGroup.id){
        this.addUserDialog =  true;
        if(!this.isFirstOpen){
          this.$refs.childDialog.onLoad(this.$refs.childDialog);
        }
        else{
          this.isFirstOpen = false;
        }
      }
      else{
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '请先选择一个左边的分组再添加！！!'
        });
      }
    },
    /**
     * 保存用户列表
     */
    handleBatchAdd(userListValue){
      this.fullscreenLoading = true;
      // 前后角色对比，给新增和删除的打上标识
      let resultList = [];
      // 原列表不存在的表示新增的元素
      let inOldValue = false;
      let inNewValue = false;
      userListValue.forEach(element => {
        inOldValue = false;
        for(var i = 0 ; i < this.oldUserListValue.length; i++){
          if (element.id == this.oldUserListValue[i]) {
            inOldValue = true;
            i = this.oldUserListValue.size + 1;
          }
        }
        //若没找到表示新增元素
        if(!inOldValue){
          resultList.push({
            userGroupId: this.currentGroup.id,
            userId: element.id,
            userName: element.userName,
            realName: element.realName,
            belongOrgNo: element.belongOrgNo,
            belongOrgName: element.belongOrgName,
            validFlag: '1'
          })
        }
      });
      if(resultList.length > 0){
        this.reqParams =  {
          transCode: '0001',
          listBody: resultList
        }
        this.commonData = reqCommonMsg(this.reqParams)
        saveOrUpdateSysUserGroupRelationList(this.commonData).then(() => {
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '添加成功!'
          });
          this.onLoad(this.page);
          userListValue = null;
          this.addUserDialog = false;
          this.fullscreenLoading = false;
        }, error => {
          //this.$console.log(error);
        });
      }
      else{
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '用户未发生变化!'
        });
        this.fullscreenLoading = false;
      }
    },
    /**
     * 机构树形菜单点击时触发事件
     */
    treeNodeClick(data){
      this.currentGroup = data
      this.onLoad(this.page)
    },
    /**
     * 加载列表数据
     */
    onLoad(page) {
      if(!this.$project.checkChooseProject()){
        return false;
      }
      this.singleBody.userGroupId=this.currentGroup.id;
      this.loading = true;
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage: page.currentPage, 
        pageSize: this.website.maxPageSize
      }
      this.commonData = reqCommonMsg(this.reqParams)
      querySysUserGroupRelationListPage(this.commonData).then(res => {
        const data = res.data.body;
        this.page.total = data.total;
        this.data = data.listBody;
        this.loading = false;
        this.oldUserListValue = [];
        this.data.forEach(element => {
          this.oldUserListValue.push(element.userId)
        });
        this.selectionClear();
      }, error => {
        this.loading = false; 
      });
    },
    /**
     * 加载用户组
     */
    onLoadUser(page){
      if(!this.$project.checkChooseProject()){
        return false;
      }
      this.loading = true;
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage: 1, 
        pageSize: this.website.maxPageSize
      }
      this.singleBody.projectId = this.projectInfo.id;
      this.commonData = reqCommonMsg(this.reqParams)
      querySysGroupInfoListPage(this.commonData).then(res => {
        const data = res.data.body.listBody; 
        data.forEach(element => {
          this.treeData.push(
            {
              id: element.id,
              userGroupName: '['+element.userGroupCategory+']'+element.userGroupName
            }
          );
        });
        this.loading = false;
      }, error => {
        this.loading = false; 
      });
    },
    /**
     * 新增一条记录
     */
    rowSave(row, done, loading) {
      this.reqParams.singleBody = row;
      this.commonData = reqCommonMsg(this.reqParams)
      saveSysUserGroupRelation(this.commonData).then(() => {
        done();
        this.singleBody={};
        this.onLoad(this.page);
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        //this.$console.log(error);
        loading();
      });         
      //this.$console.log("row = ",row ,loading)
    },
    /**
     * 修改一条记录
     */
    rowUpdate(row, index, done, loading) { 
      this.reqParams.singleBody = row;
      this.commonData = reqCommonMsg(this.reqParams)
      updateSysUserGroupRelation(this.commonData).then(() => {
        done();
        this.singleBody={}
        this.onLoad(this.page);
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        //this.$console.log(error);
        loading();
      });
      //this.$console.log('loading = ',loading)
    },
    /**
     * 删除一条记录
     */
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.singleBody = row;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteSysUserGroupRelation(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
        }).catch(() => {});
    },
    /**
     * 双击打开详细窗口
     */
    handleRowDBLClick (row, event) {
      this.$refs.crud.rowView(row,row.$index);
    },
    /**
     * 批量新增记录
     */
    openBatchAddDialog(){
      this.batchAddDialog = true;
    },
    // 
    handleImport() {
      this.loading=true;
      var dataList = new Array();
      if(this.importDataArea){
        var lineList = this.importDataArea.split('\n')
        lineList.forEach((element,index) => {
          if(element.trim() != ''){
            var field = element.split('\t')
            var fieldList = {
              belongOrgNo:field[0],
              belongOrgName:field[1],
              userId:field[2],
              userName:field[3],
              realName:field[4],
            }
            dataList[index] = fieldList
            //this.$console.log('fieldList = ',fieldList)
          }
        });
        //批量写入记录
        this.reqParams.listBody = dataList;
        this.commonData = reqCommonMsg(this.reqParams)
        saveSysUserGroupRelationList(this.commonData).then(() => {
          this.loading=false;
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
        }, error => {
          //this.$console.log(error);
          this.loading=false;
          loading();
        });      
        //this.$console.log('lineList=',dataList)
      }
      else{
        this.loading=false;
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '数据格式不正确!'
        });
      }
    },
    /**
     * 搜索重置
     */
    searchReset() {
      this.conditions =[];
      this.singleBody = {};
      this.onLoad(this.page);
    },
    /**
     * 搜索
     */
    searchChange(params, done) {
      this.singleBody = params
      this.page.currentPage = 1;
      this.onLoad(this.page);
      done();
    },
    refreshChange(){
      this.onLoad(this.page);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    /**
     * 处理批量删除
     */
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.listBody = this.ids;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteSysUserGroupRelationList(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        }).catch(() => {});
    },
    /**
     * 拷贝记录
     */
    handleCopy(row){
      this.$confirm('确定复制数据?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading=true;
        let copyValue=row;
        copyValue.id='0';
        copyValue.dataSign='0'
        copyValue.tableName='拷贝 '+ copyValue.tableName; 
        this.reqParams.singleBody = copyValue;
        this.commonData = reqCommonMsg(this.reqParams)
        saveSysToolTables(this.commonData).then(() => {
          this.singleBody={};
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
          this.loading=false;
        }, error => {
          //this.$console.log(error);
          this.loading=false;
        });
      }).catch(() => {});       
    },
    /**
     * 打开编辑、查询弹窗前查询记录
     */  
    beforeOpen(done, type) {
      this.reqParams =  {
        singleBody: {
          id:this.form.id
        }
      }
      let commonData = reqCommonMsg(this.reqParams)
      if (['edit', 'view'].includes(type)) {
        querySysUserGroupRelation(commonData).then(res => {
          this.form = res.data.body.singleBody;
        });
      }
      done();
    },
    /**
     * 翻页查询
     */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    /**
     * 更改每页条数
     */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    /**
     * 自定义查询条件
     */
    filterChange(result) {
      this.page.currentPage = 1;
      this.conditions = filterFormat(result)
      this.onLoad(this.page);
    },
    /**
     * 列表排序
     */
    sortChange(val){
      this.orderRules=val
      this.onLoad(this.page);
    },
  
    /**
     * 导出Excel
     */
    exportExcel() {
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage:1, 
        pageSize: 100
      }
      //this.$console.log('reqParams = ',this.reqParams)
      this.commonData = reqCommonMsg(this.reqParams)
      exportSysUserGroupRelationExcel(this.commonData);
    }
  },
  created() {
       
  },
  mounted() {  
    if(!this.$project.checkChooseProject()){
      return false;
    }
    this.showColumn = this.$getStore({name:  this.userInfo.userId +'sysUserGroupRelationColumn'});
  },
  watch: {
    showColumn: {
      handler(newValue, oldValue) {
        this.$setStore({name:  this.userInfo.userId+'sysUserGroupRelationColumn', content: this.showColumn});
      },
      deep: true
      //this.$setStore({name: this.userInfo.userId +'sysUserGroupRelationColumn', content: this.showColumn});
    }
  }
};
</script>
<style>
.el-main {
    margin-left: 5px !important;  
    border-left: 10px solid #f3f3f3 !important;  
}
</style>